<script setup></script>
<template>
    <el-row>
        <!-- <div>
            <h2>nihao</h2>
            <h2>{{ historyParams }}</h2>
            <h2>{{ teacher }}</h2>
            <h2>{{ teacher.avatarUrl }}</h2>
        </div> -->
        <el-col :span="4" style="text-align: center;">
            <el-upload
                class="avatar-uploader"
                action="http://localhost/nginx/uploadByAction"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
            >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
        </el-col>
        <el-col :span="17">
            <div class="text_div">
                <h3>{{ teacher.name }}</h3>
                <p>手机号: {{ teacher.phone }}</p>
                <p>性别: {{ teacher.sex }}</p>
                <p>老师介绍: {{ teacher.introduce }}</p>
                <!-- <p>备注: {{ teacher.note }}</p> -->
            </div>
        </el-col>
        <el-col :span="3">
            <el-button type="primary" @click="handleEdit">编辑信息</el-button>
            <el-button type="info" @click="goBack">返回</el-button>
        </el-col>
    </el-row>
    
    <el-divider>
    </el-divider>

    <el-tabs type="border-card">
        <!-- 老师分析区 -->
        <el-tab-pane label="上课时间轴">
            <el-timeline style="max-width: 600px">
                <el-timeline-item
                    v-for="(activity, index) in activities"
                    :key="index"
                    :color="activity.color"
                    :timestamp="activity.timestamp"
                >
                    {{ activity.content }}
                </el-timeline-item>
            </el-timeline>
        </el-tab-pane>

        <!-- 上课记录区 -->
        <el-tab-pane label="上课记录">
                
                <el-table :data="filterTableData" style="width: 100%">
                    <el-table-column label="课程名" prop="courseName" />
                    <el-table-column label="上课时间" prop="courseTime"/>
                    <el-table-column label="上课学员" prop="memberNames" />
                    <el-table-column label="次数/单人单次" prop="count"/>
                    <el-table-column align="right" width="360">
                      <template #header>
                        <el-input v-model="search" size="large" placeholder="Type to search" />
                      </template>
                    </el-table-column>
                  </el-table>

            </el-tab-pane>

    </el-tabs>


    <el-drawer v-model="drawer" direction="rtl" size="50%">
    <template #header="{ titleId, titleClass }">
      <h4 :id="titleId" :class="titleClass">This is a custom header!</h4>
    </template>
          <el-form
              ref="teacherFormRef"
              style="max-width: 600px"
              :model="teacherForm"
              :rules="rules"
              label-width="auto"
              class="add_teacher_form"
              status-icon>
              <el-form-item label="老师姓名" prop="name">
                  <el-input v-model="teacherForm.name" />
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                  <el-input v-model="teacherForm.phone" />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                  <el-input v-model="teacherForm.email" />
              </el-form-item>
           
              <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="teacherForm.sex">
                      <el-radio value="男">男</el-radio>
                      <el-radio value="女">女</el-radio>
                  </el-radio-group>
              </el-form-item>

             <el-form-item label="出生日期" prop="birthday">
                  <el-date-picker v-model="teacherForm.birthday"
                          type="date"
                          aria-label="Pick a date"
                          placeholder="选择日期"
                          style="width: 100%"/>
             </el-form-item>

             <el-form-item label="老师介绍" prop="introduce">
                  <el-input v-model="teacherForm.introduce" type="textarea" />
             </el-form-item>

             <el-form-item>
              
              <div v-if="submit">
                <el-button type="primary" @click="submitForm(teacherFormRef)">
                添加
                </el-button>
                <el-button @click="resetForm(teacherFormRef)">重置</el-button>
              </div>
                
              <div v-else>
                <el-button type="primary" @click="changeForm(teacherFormRef) ">
                保存
              </el-button>
              <el-button @click="outForm(teacherFormRef)">取消</el-button>
              </div>
              
            </el-form-item>

          </el-form>
  </el-drawer>
</template>

<script  lang="ts" setup>
//导入
import{createApp, ref , reactive , watch , computed , onMounted, toRaw} from 'vue'
import { ElMessageBox } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import GLOBAL from '@/api/global_variable'
import { handleTeacherSubmit as TeacherApi } from '../../api/teacher'
import { handleTeacherData, handleTeacherDelete, handleTeacherEdit } from '../../api/teacher'  
import loadJson from '@/http/local/loginJson'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'

//useRoute钩子用来获取当前激活的路由信息。它返回一个Route对象，这个对象包含了当前路由的所有相关信息，
// 比如params（路径参数）、query（查询参数）、name（路由名称）、path（路径）等。
const route = useRoute()
const historyParams = history.state.params.index
console.log('history.state', history.state,history.state.params.index)


const isF=ref(true)
//定义响应式对象【注：此数据应该去后台来获取】
const teacher=ref({
    name: '',
    phone: '',
    email: '',
    sex: '',
    birthday: '',
    introduce: '',
    avatarUrl: '',
    id: '',
    createTime: '',
    updateTime: '',
    createUser: '',
    updateUser: '',
    isDeleted: '',
    version: '',
    deletedTime: '',
    deletedUser: '',
})

//上课时间轴中的模拟数据，这个数据要从后端获取
const activities = ref(null)
//模拟的数据
const classRecords = ref([])
//定义异步方法来加载数据【只是模拟，这里要改的】
const getData = async () => {
    try {
        const data1 = await loadJson('demoDatas/teacher/activities.json')
        console.log(data1)
        activities.value = data1
        const { data } = await handleTeacherData()
        console.log(data)
        teacher.value = data[historyParams]
        console.log("teacher"+teacher.value)
        const imUrl=data[historyParams].avatarUrl
        console.log(imUrl)
    } catch (error) {
        ElMessage.error('请求接口报错')
        console.log(error)
    }
}
onMounted(async () => {
    getData()
}) 




//处理头像
const imageUrl = ref('https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  console.log("成功"+imageUrl.value)
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  console.log(imageUrl.value)
}


const handleAvatar = () => {
    //todo 请自行完成


}
const drawer = ref(false)
const drawerTitle = ref('添加老师')
const submit=ref(true)
const teacherFormRef = ref()
const teacherForm = reactive({
    name: '',
    phone: '',
    email: '',
    sex: '',
    birthday: '',
    introduce: '',
})



//import useUserInfoStore from '@/stores/userInfo.js'

//const uploadRef = ref()

//用户头像地址
//const userInfoStore = useUserInfoStore()
//const imgUrl= userInfoStore.getUserInfo().userPic?ref(userInfoStore.getUserInfo().userPic):avatar




const namerules2 = (rule: any, value: any, callback: any) => {
  console.log("已调用")
  console.log(teacherForm.name)
  if (teacher.value.name!=teacherForm.name)  {

    console.log("!问题!")
        callback(new Error("老师姓名不存在"))
      }
  else{
    console.log("没问题")
    callback()
  }
}
const rules=reactive({
  name: [
  {validator: namerules2, trigger: ['change','blur']},
    { required: true, message: '请输入老师姓名', trigger: 'blur' },
    { min: 1, max: 6, message: '姓名长度在1-6之间', trigger: 'blur' },
    
  ],
  phone: [
    {
      required: true,
      message: '请输入手机号码',
      trigger: 'blur',
    },
  ],
  sex: [
    {
        required: true,
        message: '请选择性别',
        trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱',
      trigger: 'blur',
    },
  ],
  birthday: [
    {
      type: 'date',
      required: true,
      message: '请选择生日',
      trigger: 'change',
    },
  ],
  introduce: [
    { required: false, message: '自我介绍', trigger: 'blur' },
  ],
})
//采用抽屉式弹层来处理更新操作
const handleEdit = () => {
    //修改抽屉title
    drawerTitle.value = '修改老师'
    //打开抽屉
    drawer.value = true

    function funct(){
        submit.value=false
    }
    funct()
    
    //给表单元素赋值
    teacherForm.name = teacher.value.name
    teacherForm.phone = teacher.value.phone
    teacherForm.email= teacher.value.email
    teacherForm.introduce=teacher.value.introduce
    teacherForm.birthday=teacher.value.birthday
    teacherForm.sex=teacher.value.sex


    //todo ...
}
const changeForm = async (formElement) => {
    console.log(formElement)

    if (!formElement) return
    //进行验证
    await formElement.validate((valid, fields) => {
        if (valid) {
            console.log(teacherForm)
            // todo 这里去提交表单数据到后端
             handleTeacherEdit(teacherForm).then(res=>{
                console.log(res)
                if(res.status==200){
                  teacher.value.name=teacherForm.name
                  teacher.value.phone=teacherForm.phone
                  teacher.value.email=teacherForm.email
                  teacher.value.introduce=teacherForm.introduce
                  teacher.value.birthday=teacherForm.birthday
                  teacher.value.sex=teacherForm.sex
                    ElMessageBox.alert('修改成功！', '修改成功', {
                        type: 'success',
                        center:true,
                    })
                }
                else{
                    ElMessageBox.alert('修改失败！', '修改失败', {
                        type: 'error',
                    })
                }
            })
            // ... 

        } else {
            console.log('表单验证失败，请重新填写', fields)
        }
    })
}

const outForm = (formElement) => {

  teacherForm.name = teacher.value.name
    teacherForm.phone = teacher.value.phone
    teacherForm.email= teacher.value.email
    teacherForm.introduce=teacher.value.introduce
    teacherForm.birthday=teacher.value.birthday
    teacherForm.sex=teacher.value.sex

}


const router = useRouter()

//返回
const goBack = () => {
    //
    router.back()
}

//老师授课录 表格区：
const search = ref('')

//这里采用计算属性 来过滤表格中的数据【只是前端过滤】
const filterTableData = computed(() => 
    classRecords.value.filter(
        (data) => !search.value || data.courseName.toLocaleLowerCase().includes(search.value.toLocaleLowerCase())
    )
)

</script>

<style>
    .text_div {
        padding: 10px 30px;
        font-size: 16px;
    }
    .text_div p {
        margin: 15px 0;
    }
    .avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  border-radius: 150px; 
  border: 5px
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  border-radius: 150px; 
  border: 5px
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 150px; 
  border: 5px
}
</style>